//
//  ZJPDFReaderView.m
//  ZJControlsClass
//
//  Created by 陈旭 on 2024/12/9.
//

#import "ZJPDFReaderView.h"
#import <PDFKit/PDFKit.h>

@interface ZJPDFReaderView () <UIPageViewControllerDataSource, UIPageViewControllerDelegate>

@property (nonatomic, strong) UIPageViewController *pageViewController;
@property (nonatomic, strong) PDFDocument *pdfDocument;
@property (nonatomic, assign) NSInteger numberOfPages;
@property (nonatomic, assign) NSInteger currentPage;
//@property (nonatomic, strong) NSURL *pdfURL;

@end

@implementation ZJPDFReaderView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.currentPage = 0;
        self.numberOfPages = 0;
    }
    return self;
}


- (void)setupPageViewController {
    if (self.pageViewController) {
        [self.pageViewController.view removeFromSuperview];
        self.pageViewController = nil;
    }
    
    UIPageViewController *pageViewController = [[UIPageViewController alloc]
        initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl
        navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
        options:nil];
    
    pageViewController.dataSource = self;
    pageViewController.delegate = self;
    
    if (self.pdfDocument) {
        UIViewController *firstPage = [self viewControllerForPage:0];
        if (firstPage) {
            [pageViewController setViewControllers:@[firstPage]
                                    direction:UIPageViewControllerNavigationDirectionForward
                                    animated:NO
                                    completion:nil];
        }
    }
    
    [self addSubview:pageViewController.view];
    pageViewController.view.frame = self.bounds;
    self.pageViewController = pageViewController;
}

- (UIViewController *)viewControllerForPage:(NSInteger)pageNumber {
    if (!self.pdfDocument || pageNumber < 0 || pageNumber >= self.numberOfPages) {
        return nil;
    }
    
    UIViewController *pageController = [[UIViewController alloc] init];
    PDFPage *page = [self.pdfDocument pageAtIndex:pageNumber];
    if (!page) {
        return nil;
    }
    
    PDFView *pdfView = [[PDFView alloc] initWithFrame:pageController.view.bounds];
    pdfView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    pdfView.displayMode = kPDFDisplaySinglePage;
    pdfView.autoScales = YES;
    pdfView.document = self.pdfDocument;
    
    [pdfView goToPage:page];
    
    [pageController.view addSubview:pdfView];
    pageController.view.tag = pageNumber;
    
    return pageController;
}

#pragma mark - Public Methods

- (void)goToPage:(NSInteger)pageNumber animated:(BOOL)animated {
    if (pageNumber < 0 || pageNumber >= self.numberOfPages) {
        return;
    }
    
    UIViewController *targetController = [self viewControllerForPage:pageNumber];
    UIPageViewControllerNavigationDirection direction =
        pageNumber > self.currentPage ? UIPageViewControllerNavigationDirectionForward :
                                      UIPageViewControllerNavigationDirectionReverse;
    
    __weak typeof(self) weakSelf = self;
    [self.pageViewController setViewControllers:@[targetController]
                                    direction:direction
                                    animated:animated
                                    completion:^(BOOL finished) {
        if (finished) {
            weakSelf.currentPage = pageNumber;
            if ([weakSelf.delegate respondsToSelector:@selector(pdfReaderDidUpdateCurrentPage:totalPages:)]) {
                [weakSelf.delegate  pdfReaderDidUpdateCurrentPage:weakSelf.currentPage totalPages:weakSelf.numberOfPages];
            }
        }
    }];
}

- (void)setPdfURL:(NSURL *)pdfURL  {
    if (!pdfURL) {
        return;
    }
    
    _pdfURL = pdfURL;
    
    PDFDocument *document = [[PDFDocument alloc] initWithURL:pdfURL];
    if (!document) {
        NSLog(@"Failed to load PDF document from URL: %@", pdfURL);
        return;
    }
    
    self.pdfDocument = document;
    self.numberOfPages = self.pdfDocument.pageCount;
    self.currentPage = 0;
    
    [self setupPageViewController];
    
    if ([self.delegate respondsToSelector:@selector(pdfReaderDidUpdateCurrentPage:totalPages:)]) {
        [self.delegate pdfReaderDidUpdateCurrentPage:self.currentPage totalPages:self.numberOfPages];
    }
}

// 新增前一页方法
- (void)goToPreviousPage:(BOOL)animated {
    if (self.currentPage > 0) {
        [self goToPage:self.currentPage - 1 animated:animated];
    }
}

// 新增下一页方法
- (void)goToNextPage:(BOOL)animated {
    if (self.currentPage < self.numberOfPages - 1) {
        [self goToPage:self.currentPage + 1 animated:animated];
    }
}

#pragma mark - UIPageViewControllerDataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
      viewControllerBeforeViewController:(UIViewController *)viewController {
    NSInteger currentIndex = viewController.view.tag;
    return [self viewControllerForPage:currentIndex - 1];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
       viewControllerAfterViewController:(UIViewController *)viewController {
    NSInteger currentIndex = viewController.view.tag;
    return [self viewControllerForPage:currentIndex + 1];
}

#pragma mark - UIPageViewControllerDelegate

- (void)pageViewController:(UIPageViewController *)pageViewController
        didFinishAnimating:(BOOL)finished
   previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers
       transitionCompleted:(BOOL)completed {
    if (completed) {
        self.currentPage = pageViewController.viewControllers.firstObject.view.tag;
        if ([self.delegate respondsToSelector:@selector(pdfReaderDidUpdateCurrentPage:totalPages:)]) {
            [self.delegate pdfReaderDidUpdateCurrentPage:self.currentPage totalPages:self.numberOfPages];
        }
    }
}

@end
